package org.wmq.travelagency02.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.wmq.travelagency02.mapper.GuidebookMapper;
import org.wmq.travelagency02.model.Entity.ChatUser;
import org.wmq.travelagency02.model.Entity.Guidebook;
import org.wmq.travelagency02.model.Entity.TourGroup;
import org.wmq.travelagency02.service.ChatUserService;
import org.wmq.travelagency02.service.GuidebookService;
import org.wmq.travelagency02.service.TourGroupService;

import java.util.List;

@Service
@RequiredArgsConstructor
public class GuidebookServiceImpl extends ServiceImpl<GuidebookMapper, Guidebook> implements GuidebookService{
    @Autowired
    private  TourGroupService tourGroupService;
    @Autowired
    private ChatUserService chatUserService;

    @Override
    public Guidebook getById(Long id) {
        LambdaQueryWrapper<Guidebook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Guidebook::getId,id).select(
                Guidebook::getName,
                Guidebook::getPhone,
                Guidebook::getGender,
                Guidebook::getAge,
                Guidebook::getIsAdmin
        );
        Guidebook result = this.getOne(queryWrapper);
        if (result == null) {
            return null;
        }
        result.setId(id);
        return result;
    }

    @Override
    public boolean removeById(Long id) {
        List<TourGroup> tourGroupList = this.tourGroupService.lambdaQuery().select(TourGroup::getGuidebookId).list();
        for (TourGroup tourGroup : tourGroupList) {
            if (tourGroup.getGuidebookId().equals(id)){
                return false;
            }
        }
        return super.removeById(id);
    }

    @Override
    public boolean addChatUserId(String chatUserId, Long id) {
        Guidebook guidebook = new Guidebook();
        guidebook.setId(id);
        guidebook.setChatUserId(chatUserId);
        return this.updateById(guidebook);
    }

    @Override
    public ChatUser getChatUser(Long id) {
        Guidebook guidebook = this.lambdaQuery().eq(Guidebook::getId, id)
                .select(Guidebook::getChatUserId).one();
        if (guidebook == null){
            return null;
        }
        if (guidebook.getChatUserId() == null){
            return null;
        }
        return this.chatUserService.getById(guidebook.getChatUserId());
    }
}
